﻿/// <reference path="../../js/utils.js" />
'use strict';

define([
    'screenView',

    'screens/employers/workerDetails/model',
    'screens/employers/workerDetails/view',

    'screens/employers/workersTable/model',
    'screens/employers/workersTable/view',
], function (ScreenView, WorkerDetailsModel, WorkerDetailsView, WorkersTableModel, WorkersTableView) {
    var View = ScreenView.extend({
        currentWorkDetViewSel: null,
        workerDetailsViews: {},
        workerDetailsTpl: '',
        workersTableView: null,
        workersTableTpl: '',

        initialize: function (options) {
            View.__super__.initialize.apply(this, [options]);

            this.listenTo(this.model, 'change:workers', _.bind(this._model_ChangedWorkers, this));

            this.refreshData();

            return this;
        },
        render: function (workerIdSel) {
            View.__super__.render.apply(this);

            var workers = this.model.get('workers');

            /* First render actions. */
            if (!this.rendered) {
                var screensForlderUrl = App.config.get('screensFolderUrl');

                this.workerDetailsTpl = Handlebars.compile(utils.templating.load(
                    sprintf('%s/%s/workerDetails/template.html', screensForlderUrl, this.id)));
                this.workersTableTpl = Handlebars.compile(utils.templating.load(
                    sprintf('%s/%s/workersTable/template.html', screensForlderUrl, this.id)))


                this.workersTableView = new WorkersTableView({
                    el: this.$el.find(sprintf('#workersTableContainer_%s', this.id)),
                    /* Pass a clone to the view model to prevent references. */
                    model: new WorkersTableModel({ workers: _.clone(workers) }),
                    template: this.workersTableTpl,
                });
                this.listenTo(this.workersTableView, 'added', _.bind(this._workersTableView_Added, this));
                this.listenTo(this.workersTableView.model, 'change:selectedWorkerId', _.bind(this._workersTableView_ChangeSelectedWorkerId, this));


                this.workersDetailsPanel = this.$el.find(sprintf('#workerPanelsContainer_%s', this.id));


                /* Indicates that the view was rendered at least one time. */
                this.rendered = true;
            }
            /* Not first render actions. */
            else {
                var fn_eachWorkerDetView = function (viewId, view) {
                    /* Remove next hr dom element if exists. */
                    view.$el.next('hr').remove();

                    view.destroy();
                };

                this.currentWorkDetViewSel = null;

                $.each(this.workerDetailsViews, fn_eachWorkerDetView);

                this.workerDetailsViews = {};
            }


            /* All renders actions. */
            var that = this,
                fn_eachWorker = function (index, worker) {
                    var workerDetView = new WorkerDetailsView({
                        /* Pass a clone to the view model to prevent references. */
                        model: new WorkerDetailsModel(_.clone(worker)),
                        template: that.workerDetailsTpl,
                    });

                    workerDetView.render();

                    that.workerDetailsViews[worker.id] = workerDetView;

                    that.workersDetailsPanel
                        .append(workerDetView.el)
                        .append('<hr class="hr-large"/>');

                    that.listenTo(workerDetView, 'deleted', that._workerDetModel_Deleted, that);
                    that.listenTo(workerDetView, 'edited', that._workerDetModel_Edited, that);
                    that.listenTo(workerDetView.model, 'change:selected', that._workerDetModel_Selected, that);
                };

            this.workersTableView.render();

            $.each(workers, fn_eachWorker);

            return this;
        },

        addWorker: function (worker) {
            if (worker) {
                var that = this,
                    fn_success = function (response) {
                        if ((response) && (response.id == 0) && (response.data))
                            that.refreshData(true, response.data.id);
                    };

                App.proxy.addEmployer(
                    worker,
                    {
                        success: fn_success,
                    });
            }

            return this;
        },
        refreshData: function (render, workerIdSel) {
            var that = this,
                fn_success = function (data) {
                    that.model.set('workers', data, { silent: !render, });

                    if (render)
                        that.selectWorker(workerIdSel);
                };

            App.proxy.getEmployers({
                success: fn_success,
            });
        },
        removeWorker: function (workerId) {
            if (workerId) {
                var workers = this.model.get('workers'),
                    fn_find = function (item, index) {
                        if (item.Id == workerId)
                            return true;
                    };

                workers.remove(_.indexOf(workers, _.find(workers, fn_find)));

                this.model.set('workers', workers);
            }

            return this;
        },
        selectWorker: function (workerId) {
            if (this.currentWorkDetViewSel)
                this.currentWorkDetViewSel.setSelected(false, { silent: true });

            this.currentWorkDetViewSel = this.workerDetailsViews[workerId];

            this.workersTableView.setItemSelected(workerId, { silent: true });
            this.currentWorkDetViewSel.setSelected(true, { silent: true });

            return this;
        },
        updateWorker: function (worker) {
            if (worker) {
                var that = this,
                    fn_success = function (response) {
                        if ((response) && (response.id == 0) && (response.data))
                            that.refreshData(true, response.data.id);
                    };

                App.proxy.updateEmployer(
                    worker,
                    {
                        success: fn_success,
                    });
            }

            return this;
        },

        _model_ChangedWorkers: function (sender, worker) {
            this.render();
        },
        _workerDetModel_Deleted: function (sender, worker) {
            this.removeWorker(worker.id);
        },
        _workerDetModel_Edited: function (sender, worker) {
            this.updateWorker(worker);
        },
        _workerDetModel_Selected: function (sender, value, options) {
            if (value)
                this.selectWorker(sender.get('id'));
        },
        _workersTableView_Added: function (sender, worker) {
            this.addWorker(worker);
        },
        _workersTableView_ChangeSelectedWorkerId: function (sender, value, options) {
            this.selectWorker(value);
        },
    });

    return View;
});